import { useUserStore } from '@/stores'
import { createRouter, createWebHistory } from 'vue-router'

// 回顾Vue2的路由实现
// 1. import vueRouter from vue-router
// 2. const router = new vueRouter({routes:[],mode:hash})
// 3. 路由模式：history、hash

// Vue3的路由
// 1、创建路由实例 createRouter(配置对象)
// 2、routes  --路由规则
// 3、history --路由模式  createWebHistory使用的是hash路由模式

const router = createRouter({
  // import.meta.env.BASE_URL 路由的前缀
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/login',
      component: () => import('@/views/login/index.vue'),
      meta: { title: '登录' }
    },
    {
      path: '/',
      component: () => import('@/views/layout/index.vue'),
      redirect: '/home',
      children: [
        {
          path: '/home',
          component: () => import('@/views/Home/index.vue'),
          meta: { title: '首页' }
        },
        {
          path: '/article',
          component: () => import('@/views/Article/index.vue'),
          meta: { title: '医疗百科' }
        },
        {
          path: '/user',
          component: () => import('@/views/User/index.vue'),
          meta: { title: '个人中心' }
        },
        {
          path: '/notify',
          component: () => import('@/views/Notify/index.vue'),
          meta: { title: '消息通知' }
        }
      ]
    },
    {
      path: '/user/patient',
      component: () => import('@/views/User/PatientPage.vue'),
      meta: {
        title: '家庭档案'
      }
    }
  ]
})

// 路由权限控制
router.beforeEach((to) => {
  //  return true | return | 什么都不写 表示放行
  // 控制到某个页面  return '路由地址'
  const whitePath = ['/login']
  const store = useUserStore()
  document.title = to.meta.title as string // 修改title信息
  if (!store.user?.token && !whitePath.includes(to.path)) return '/login'
})

export default router
